package com.richapp.launcher.net.box.udp;

import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jack.netty.log.LoggerManager;
import com.jack.util.string.StringUtil;
import com.richapp.launcher.control.PageControl;
import com.richapp.launcher.database.system.dao.BoxModelDao;
import com.richapp.launcher.database.system.mode.BoxModel;
import com.richapp.launcher.net.box.message.AreYouThereRequest;
import com.richapp.launcher.net.mobile.message.BoxInfoReply;
import com.richapp.launcher.ui.activities.CreateQRCodeActivity;
import com.richapp.launcher.utils.Constants;
import com.richapp.net.udp.broadcast.server.UDPBroadCastMessageListener;
import com.richapp.net.udp.broadcast.server.UDPBroadCastServer;


import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

public class NetUDPBroadcastServer {

	private static final String TAG = NetUDPBroadcastServer.class.getName();

	private static NetUDPBroadcastServer instance = null;
	private static UDPBroadCastServer broadcastServer = null;
	private boolean boxCheckThreadRunFlag = false;
    private Context context;

	private NetUDPBroadcastServer() {
		if(broadcastServer == null){
			broadcastServer = new UDPBroadCastServer();
		}
	}
	
	public static NetUDPBroadcastServer getInstance(){
		if(instance == null){
			instance = new NetUDPBroadcastServer();
		}
		return instance;
	}

	public void start(){
		broadcastServer.start();
		setBoxCheckThreadRunFlag(true);
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(isBoxCheckThreadRunFlag()){
					try {
                        AreYouThereRequest aytr = new AreYouThereRequest();
                        aytr.setBoxInfo(new BoxModelDao(context).getCurrentBox());
                        String message = JSON.toJSONString(aytr);
						sendUDPBroadcastMessage(message);
						Thread.sleep(Constants.BOX_UDP_REMOTE_REQUEST_TIME*1000);
					} catch (Exception e) {
						Log.v("error", e.getMessage());
					}
				}
			}
		}).start();
	}
	
	public void stop(){
		broadcastServer.stop();
		setBoxCheckThreadRunFlag(false);
	}
	
	public void setBoroacastMessageListener(UDPBroadCastMessageListener listener){
		broadcastServer.setUdpBroadcastMessageListener(listener);
	}
	
	public void sendUDPBroadcastMessage(String message){
		broadcastServer.sendMessage(Constants.CONNECTION_UDP_BROADCAST_IP, Constants.CONNECTION_UDP_BROADCAST_PORT, message);
	}

    public void sendUDPBroadcastMessage(String ip, int port ,String message){
        broadcastServer.sendMessage(ip, port, message);
    }

	public boolean isBoxCheckThreadRunFlag() {
		return boxCheckThreadRunFlag;
	}

	public void setBoxCheckThreadRunFlag(boolean boxCheckThreadRunFlag) {
		this.boxCheckThreadRunFlag = boxCheckThreadRunFlag;
	}

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }


	//type = 11 UDP 组播打开主机二维码界面消息(手机->机顶盒)
	public void doOpenQRcode(String fromIp,int port,JSONObject jsonObject){

		//如果屏幕不亮，自动点亮屏幕
		PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
		if(!powerManager.isScreenOn()){
			PageControl.getInstance().power();
		}

		Intent intent = new Intent(context, CreateQRCodeActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}

	//type = 12 UDP 组播关闭主机二维码界面消息(手机->机顶盒)
	public void doCloseQRcode(String fromIp,int port,JSONObject jsonObject){
		Intent closeactivity = new Intent();
		closeactivity.setAction(CreateQRCodeActivity.CLOSEACTIVITYTAG);
		context.sendBroadcast(closeactivity);
	}

	//type 29 手机端UDP查找指定主机信息
	public void doSearchHost(String fromIp, int fromPort, JSONObject jsonObject){
		BoxModel currentBox = new BoxModelDao(context).getCurrentBox();
		String boxCpuId = jsonObject.getString("boxCpuId");
		if(StringUtil.isNullOrEmpty(boxCpuId)){
			boxCpuId = jsonObject.getString("currentBoxCpuId");
		}

		String key = jsonObject.getString("key");
		if("ufo".equals(key)){

		}else{
			if(StringUtil.isNullOrEmpty(boxCpuId)){
				LoggerManager.getInstance().getiLogger().error(getClass(),"boxCpuId 或者currentBoxCpuId为空");
				return;
			}

			if(!currentBox.getBoxCpuId().equals(boxCpuId)){
				return;
			}
		}

		int port;
		try{
			port = jsonObject.getInteger("port");
		}catch (Exception e){
			Log.e(TAG,"读取手机端port错误:"+e.getMessage());
			return;
		}

		BoxInfoReply bir = new BoxInfoReply();
		bir.setBoxInfo(currentBox);
		bir.setCurrentBoxCpuId(currentBox.getBoxCpuId());

		final String message = JSON.toJSONString(bir);
		final String sip = fromIp;
		final int sport = port;
		new Thread(new Runnable() {
			@Override
			public void run() {
				try{
					DatagramSocket datagramSocket = new DatagramSocket();
					byte[] bytes = message.getBytes("UTF8");
					DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getByName(sip),sport);
					datagramSocket.send(packet);
				}catch (Exception e){
					Log.e(TAG,"发送UDP单播失败:"+e.getMessage());
				}
			}
		}).start();
	}
}
